package com.maple.threadLocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>使用ThreadLocal</p>
 *
 * @author maple
 */
public class MyThreadLocalByThreadLocal {

    // ThreadLocal方法在多线程并行的情况下，每个线程内都有自己独享的对象
    // 线程安全
    // 不需要加锁，执行效率高
    // 更高效的利用内存，节省开销 相比于每个任务都建一个SimpleDateFormat，显然用ThreadLocal可以节省内存和开销
    // 注意：最后一次使用之后应该手动的调用remove()方法，防止内存泄露
    private static final ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));

    public static String date(int seconds) {
        Date date = new Date(1000L * seconds);
        SimpleDateFormat sdf = simpleDateFormatThreadLocal.get();
        return sdf.format(date);
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    String date = date(finalI);
                    System.out.println(date);
                }
            });
        }
        executorService.shutdown();
    }
}
